package com.mezz.bones.im.gateway.util;

import com.mezz.bones.im.common.result.ImResult;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: zhuang
 * @Date: 2024/12/5 17:59
 * @Description: TODO
 * @Version: 1.0
 **/

@Slf4j
public class ChannelUtil {

    public static void sendAndGracefullyClose(ChannelHandlerContext ctx, ImResult message) {

        sendAndGracefullyClose(ctx.channel(),message);

    }

    public static void sendAndGracefullyClose(Channel ctx, ImResult message) {

        // 发送消息并获得 ChannelFuture
        ChannelFuture future = ctx.writeAndFlush(message);


        // 监听消息发送完成的状态
        future.addListener(f -> {
            if (f.isSuccess()) {
                //确保消息发送成功后再关闭连接 底层会调用close方法
                ctx.writeAndFlush(new CloseWebSocketFrame(1000, "Server is shutting down"));

            } else {
                // 发送失败时处理失败逻辑，通常也是关闭连接
                log.error("消息发送失败，准备关闭连接");
                ctx.writeAndFlush(new CloseWebSocketFrame(1000, "Server is shutting down"));
            }
        });

    }
}
